package com.terracloud.server.controller;

import com.google.common.util.concurrent.ListenableFuture;
import com.terracloud.common.util.AsyncUtils;
import com.terracloud.server.common.data.exception.ThingsboardException;
import com.terracloud.server.common.data.id.DeviceId;
import com.terracloud.server.queue.util.TbCoreComponent;
import com.terracloud.server.service.executors.RpcCallbackExecutorService;
import com.terracloud.server.service.security.model.SecurityUser;
import com.terracloud.server.vo.BatchDeviceRpcCommandVo;
import com.terracloud.server.vo.DeviceRpcCommandVo;
import io.swagger.v3.oas.annotations.Parameter;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.UUID;

import static com.terracloud.server.controller.ControllerConstants.DEVICE_ID_PARAM_DESCRIPTION;

/**
 *
 * @author chenhainan
 * @since 2025/11/7
 */
@RestController
@RequiredArgsConstructor
@RequestMapping(TbUrlConstants.RPC_V2_URL_PREFIX + "/batch")
@Slf4j
public class RpcBatchController extends AbstractRpcController {

    private final RpcCallbackExecutorService rpcCallbackExecutorService;

    @RequestMapping(value = "/oneway", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<Boolean> handleOneWayDeviceRPCRequest(
            @Valid @NotNull @RequestBody BatchDeviceRpcCommandVo batchDeviceRpcCommandVo) throws ThingsboardException {
        final var deviceRpcCommand = batchDeviceRpcCommandVo.getDeviceRpcCommand();
        final var currentUser = getCurrentUser();
        for (var deviceId : batchDeviceRpcCommandVo.getDeviceIds()) {
            rpcCallbackExecutorService.execute(() -> {
                try {
                    handleDeviceRPCRequest(currentUser,true, new DeviceId(UUID.fromString(deviceId)), deviceRpcCommand,
                            HttpStatus.GATEWAY_TIMEOUT, HttpStatus.GATEWAY_TIMEOUT);
                } catch (ThingsboardException e) {
                    log.error("设备 [{}] 执行 rpc 任务 [{}]发生错误", deviceId, deviceRpcCommand, e);
                }
            });
        }
        return ResponseEntity.ok(true);
    }

}
